package apis

import (
	"github.com/gin-gonic/gin"
	"tylnmall/models"
	"github.com/jinzhu/gorm"
	"common/logger"
	"net/http"
	"tylnmall/constant"
	"errors"
	"tylnmall/service"
	"math"
	"fmt"
	"strings"
	"time"
)

type st struct {
	Id          int    `json:"id" form:"id"`
	Name        string `json:"name" form:"name"`                   //商铺名称
	Introduce   string `json:"introduce" form:"introduce"`         //介绍
	Image       string `json:"image" form:"image"`                 //图片
	UserOwnerId int    `json:"user_owner_id" form:"user_owner_id"` //所有者id
	CreateTime  string `json:"create_time" form:"create_time"`     //创建时间
	Address     string `json:"address" form:"address"`             //地址
	Phone       string `json:"phone" form:"phone"`                 //联系方式
	Num         int    `json:"num"`                                //所有商品数量
}

func StoryListApi(c *gin.Context) {
	type param struct {
		Page int `json:"page" form:"page"`
	}
	var p param
	var storys []*models.Story
	var err error
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	var count float64
	if err := db.Model(&models.Story{}).Count(&count).Error; err != nil {
		logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	if p.Page == 0 {
		p.Page = 1
	} else if float64(p.Page) > math.Ceil(count/100.0) {
		p.Page = 1
	}
	if err = db.Limit(100).Offset((p.Page - 1) * 100).Find(&storys).Error; err != nil {
		logger.Error(err)
		err = errors.New("story not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	var sts []*st
	for _, story := range storys {
		var s st
		s.Num = 0
		s.Id = story.Id
		s.Name = story.Name
		s.Introduce = story.Introduce
		s.Image = story.Image
		s.UserOwnerId = story.UserOwnerId
		s.Address = story.Address
		s.Phone = story.Phone
		s.CreateTime = story.CreateTime
		_, s.Num = service.CommodityNum(story.Id, *db)
		sts = append(sts, &s)
	}
	c.JSON(http.StatusOK, gin.H{"story": sts, "pageNum": math.Ceil(count / 100.0), "storyNum": count})
}

func StoryFindByIdApi(c *gin.Context) {
	type param struct {
		Id int `json:"id" form:"id"`
	}
	var p param
	var story models.Story
	var err error
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Where("id = ?", p.Id).Find(&story).Error; err != nil {
		logger.Error(err)
		err = errors.New("story not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	var s st
	s.Num = 0
	s.Id = story.Id
	s.Name = story.Name
	s.Introduce = story.Introduce
	s.Image = story.Image
	s.UserOwnerId = story.UserOwnerId
	s.Address = story.Address
	s.Phone = story.Phone
	s.CreateTime = story.CreateTime
	_, s.Num = service.CommodityNum(story.Id, *db)
	c.JSON(http.StatusOK, gin.H{"story": s})
}

func StoryFindByNameApi(c *gin.Context) {
	type param struct {
		Name string `json:"name" form:"name"`
		Page int    `json:"page" form:"page"`
	}
	var p param
	var storys []*models.Story
	var err error
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	var count float64
	if err := db.Where("name like ?", "%"+p.Name+"%").Model(&models.Story{}).Count(&count).Error; err != nil {
		logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	if p.Page == 0 {
		p.Page = 1
	} else if float64(p.Page) > math.Ceil(count/8.0) {
		p.Page = 1
	}
	if err = db.Limit(8).Offset((p.Page - 1) * 8).Where("name like ?", "%"+p.Name+"%").Find(&storys).Error; err != nil {
		logger.Error(err)
		err = errors.New("story not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	var sts []*st
	for _, story := range storys {
		var s st
		s.Num = 0
		s.Id = story.Id
		s.Name = story.Name
		s.Introduce = story.Introduce
		s.Image = story.Image
		s.UserOwnerId = story.UserOwnerId
		s.Address = story.Address
		s.Phone = story.Phone
		s.CreateTime = story.CreateTime
		_, s.Num = service.CommodityNum(story.Id, *db)
		sts = append(sts, &s)
	}
	c.JSON(http.StatusOK, gin.H{"story": sts, "pageNum": math.Ceil(count / 8.0), "storyNum": count})
}

func StoryAddApi(c *gin.Context) {
	var story models.Story
	var err error
	var errMsg string
	db := c.MustGet("ty").(*gorm.DB)
	if err = c.Bind(&story); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if story.Name == "" {
		errMsg += " name is error"
	}
	if story.Phone == "" || len(story.Phone) > 11 {
		errMsg += " phone is error"
	}
	if story.Address == "" {
		errMsg += " address is error"
	}
	if story.Image == "" {
		errMsg += "image is error"
	}
	if story.UserOwnerId == 0 {
		errMsg += " story is error"
	} else if b, user := service.IsUser(db, story.UserOwnerId); !b {
		fmt.Println(user.Id)
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	const base_format = "2006-01-02 15:04:05"
	//获取当前时间
	nt := time.Now()
	var timeStr = nt.Format(base_format)
	story.CreateTime = timeStr

	if errMsg != "" {
		err = errors.New(errMsg)
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}

	if err = db.Create(&story).Error; err != nil {
		logger.Error(err)
		err = errors.New("story not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"story": story, "status": "success"})
}

//商铺信息修改
func StoryUpdateApi(c *gin.Context) {
	type param struct {
		Id          int    `json:"id" form:"id"`
		Name        string `json:"name" form:"name"`                   //商铺名称
		Introduce   string `json:"introduce" form:"introduce"`         //介绍
		Image       string `json:"image" form:"image"`                 //图片
		UserOwnerId int    `json:"user_owner_id" form:"user_owner_id"` //所有者id
		Address     string `json:"address" form:"address"`             //地址
		Phone       string `json:"phone" form:"phone"`                 //联系方式
	}
	var story models.Story
	var p param
	var err error
	var b bool
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if p.Id == 0 {
		err = errors.New("StoryId not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	//fmt.Println(p)
	//fmt.Println(p.Id)
	db := c.MustGet("ty").(*gorm.DB)
	if b, story = service.IsStory(*db, p.Id); !b {
		err = errors.New("StoryId not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if err = db.Model(&story).Update(&p).Error; err != nil {
		logger.Error(err)
		err = errors.New("story not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"story": story, "status": "success"})
}

//商铺资质文件获取
func QualificationListApi(c *gin.Context) {
	type param struct {
		Id int `json:"id" form:"id"`
	}
	var p param
	var err error
	var qual []*models.Qualification
	var story models.Story
	var b bool
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if b, story = service.IsStory(*db, p.Id); !b {
		err = errors.New("StoryId not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if err = db.Where("story_id = ?", story.Id).Find(&qual).Error; err != nil {
		logger.Error(err)
		err = errors.New("qualification not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"list": qual})
}

//商铺资质文件删除
func QualificationDeleteApi(c *gin.Context) {
	type param struct {
		Id       int    `json:"id" form:"id"`             //商铺列表
		Quallist string `json:"quallist" form:"quallist"` //需要删除的资质文件id列表,格式为数组
	}
	var p param
	var err error
	var qual models.Qualification
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if b, story := service.IsStory(*db, p.Id); !b {
		fmt.Println(story)
		err = errors.New("StoryId not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	var list []string
	list = strings.Split(p.Quallist, ",")
	fmt.Println(list)
	if len(list) <= 0 {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if err = db.Where("id in (?)", list).Delete(&qual).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

//商铺资质文件添加
func QualificationAddApi(c *gin.Context) {
	type param struct {
		Id   int    `json:"id" form:"id"`
		Urls string `json:"urls" form:"urls"`
	}
	var p param
	var err error
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if b, story := service.IsStory(*db, p.Id); !b {
		fmt.Println(story)
		err = errors.New("StoryId not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	var list []string
	list = strings.Split(p.Urls, ",")
	fmt.Println(list)
	if len(list) <= 0 {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	//if p.Url == "" {
	//	err = errors.New("url is not found")
	//	logger.Error(err)
	//	c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
	//	return
	//}
	for _, url := range list {
		if url == "" {
			err = errors.New("url is not found")
			logger.Error(err)
			continue
		}
		var qual models.Qualification
		qual.StoryId = p.Id
		qual.QualificationUrl = url
		if err = db.Create(&qual).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
	}
	//var qual models.Qualification
	//qual.StoryId = p.Id
	//qual.QualificationUrl = p.Url
	//if err = db.Create(&qual).Error; err != nil {
	//	logger.Error(err)
	//	c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
	//	return
	//}
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}
